package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("dish")
@Slf4j
public class DishController {
    @Resource
    private DishService dishService;
    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 菜品信息分页查询
     * @param page 分页条件 : 页数
     * @param pageSize  每页条数
     * @param name :查询条件
     * @return 查询结果
     */
    @GetMapping("/page")
    public R<Page<DishDto>> page(int page, int pageSize, String name){
        log.info("菜品信息分页查询: name = {}:",name);
        //调用业务层
        Page<DishDto> pageInfo = dishService.pageDishDto(page, pageSize, name);
        return R.success(pageInfo);
        /*//查询菜品信息
        //分页构造器
        Page<Dish> dishPage = new Page<>(page,pageSize);
        //查询条件
        LambdaQueryWrapper<Dish> queryWrapper = Wrappers.lambdaQuery(Dish.class)
                .like(name != null, Dish::getName, name)
                .orderByDesc(Dish::getUpdateTime);

        //查询
        dishService.page(dishPage, queryWrapper);
        //定义 DishDto 分页构造器
        Page<DishDto> dishDtoPage = new Page<>(page, pageSize);

        //复制对象 copy 排除records属性
        BeanUtils.copyProperties(dishPage, dishDtoPage,"records");
        //查询条件
        List<Dish> records = dishPage.getRecords();
        //查询 获取 菜品名称
        List<DishDto> list = records.stream().map(dish -> {
            DishDto dishDto = new DishDto();
            //复制对象 copy
            BeanUtils.copyProperties(dish, dishDto);
            Category category = categoryService.getById(dish.getCategoryId());
            String category_name = category.getName();
            dishDto.setCategoryName(category_name);
            return dishDto;
        }).collect(Collectors.toList());

        //设置records属性
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);*/
    }

    /**
     * 根据id查询菜品( 包括口味信息)
     * @return 查询结果
     */
    @GetMapping("{id}")
    public R<DishDto> getById( @PathVariable Long id){
        log.info("查询菜品信息: id为{}",id);
        DishDto dishDto = dishService.findByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 新增菜品
     * @param dishDto 新增菜品信息
     * @return  操作结果
     */
    @CacheEvict(cacheNames = "dish", allEntries = true)
    @PostMapping
    public R<String> saveDishWithFlavor(@RequestBody DishDto dishDto){
        log.info("新增菜品:\n{}",dishDto);

        dishService.saveWithFlavor(dishDto);

        //清除redis缓存
       /* Set keys = redisTemplate.keys("dish*");
        redisTemplate.delete(keys);*/

        return R.success("新增菜品成功");
    }

    /**
     * 根据id查询菜品信息 ,( 包括口味信息)
     * @param dishDto 菜品信息
     * @return 查询结果
     */
    @PutMapping()
    public R<String> updateById(@RequestBody DishDto dishDto){
        log.info("修改菜品信息:{}",dishDto);
        dishService.updateWithFlavor(dishDto);
        return R.success("修改成功");
    }

    /**
     * 修改菜品禁售 ,启售状态
     * @param status 状态
     * @param ids 修改的caipinid
     * @return 修改结果
     */
    @CacheEvict(cacheNames = "dish", allEntries = true)
    @PostMapping("/status/{status}")
    public R<String> updateStatusById(@PathVariable int status, Long[] ids){
        //清除redis缓存
       /* Set keys = redisTemplate.keys("dish*");
        redisTemplate.delete(keys);*/
        //修改菜品状态
        dishService.lambdaUpdate()
                .in(Dish::getId, Arrays.asList(ids))
                .set(Dish::getStatus, status)
                .update();

        return R.success("修改状态成功");
    }

    /**
     * 根据id删除菜品 (包括口味)
     * @param ids 菜品id集合
     */
    /*
     CacheEvict 作用: 清理指定缓存
	cacheNames属性：缓存的名称，每个缓存名称下面可以有多个key
	key: 缓存的key  ----------> 支持Spring的表达式语言SPEL语法
	 allEntries属性：清楚所有的key */
    @CacheEvict(cacheNames = "dish", allEntries = true)
    @DeleteMapping()
    public R<String> deleteById(Long[] ids){
        //清除redis缓存
        /*Set keys = redisTemplate.keys("dish*");
        redisTemplate.delete(keys);*/
        //调用业务层
        dishService.deleteByIds(ids);

        return R.success("删除成功");
    }

    /**
     * 根据条件查询 菜品信息 ( 包括口味信息)
     * @param dish 菜品分类id ,菜品名称
     * @return 查寻结果
     */
    @GetMapping("/list")
    @Cacheable( cacheNames = "dish", key = "#dish.categoryId+':' +#dish.name")
    public R<List<DishDto>> list(Dish dish){
        log.info("查询菜品信息:{}", dish);
        /*List<Dish> dishList = dishService.lambdaQuery()
                .eq(Dish::getStatus, 1) //启售状态
                .like(StringUtils.isNotBlank(dish.getName()), Dish::getName, dish.getName())
                .eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId())
                .orderByAsc(Dish::getSort)
                .orderByDesc(Dish::getUpdateTime)
                .list();*/
        //redis的key
        /*String redisKey = "dish_" + dish.getCategoryId() + dish.getName();*/
        //先去redis中查询数据
        /*List<DishDto> dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(redisKey);
        if (dishDtoList != null){
            return R.success(dishDtoList);
        }*/

        List<DishDto> dishDtos = dishService.listWithFlavor(dish);
        //将数据库查询的数据存入Redis中
        /*redisTemplate.opsForValue().set(redisKey, dishDtos);*/

        return R.success(dishDtos);
    }

}
